#include <queue>
#include <stdio.h>
#include <string.h>
using namespace std;
struct s
{
  int x;    //坐标X
  int y;    //坐标Y
  int step; //所用步数
  friend bool operator<(s a, s b)
  {
    return a.step > b.step; //优先走步数小的
  }
};
int book[310][310];  //记录是否有走过
char map_[310][310]; //存入地图
int main()
{
  int n, m;
  while (scanf("%d%d", &n, &m) != EOF)
  {
    if (n == 0 && m == 0)
      return 0;
    priority_queue<s> q;
    memset(book, 0, sizeof(book));
    memset(map_, 0, sizeof(map_));
    int x1 = 0, y1 = 0;
    for (int i = 0; i < n; i++)
    {
      getchar();
      for (int j = 0; j < m; j++)
      {
        scanf("%c", &map_[i][j]);
        if (map_[i][j] == 'Y')
        {
          x1 = i;
          y1 = j;
        }
      }
    }
    s start;
    start.x = x1;
    start.y = y1;
    start.step = 0;
    q.push(start);
    int flag = 0;
    while (!q.empty())
    {
      s temp = q.top();
      q.pop();
      int next[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
      for (int i = 0; i < 4; i++) //向四个方向找
      {
        s tmp;
        tmp.x = temp.x + next[i][0];
        tmp.y = temp.y + next[i][1];
        if (tmp.x > n || tmp.y > m || tmp.x < 0 || tmp.y < 0)
          continue;
        if (book[tmp.x][tmp.y] == 0)
        {
          if (map_[tmp.x][tmp.y] == 'B')
          {
            tmp.step = temp.step + 2;
            book[tmp.x][tmp.y] = 1;
            q.push(tmp);
          }
          else if (map_[tmp.x][tmp.y] == 'E')
          {
            tmp.step = temp.step + 1;
            book[tmp.x][tmp.y] = 1;
            q.push(tmp);
          }
          else if (map_[tmp.x][tmp.y] == 'T')
          {
            tmp.step = temp.step + 1;
            flag = 1;
            printf("%d\n", tmp.step);
            break;
          }
        }
      }
      if (flag == 1)
      {
        break;
      }
    }
    if (flag == 0)
    {
      printf("-1\n");
    }
  }
}
